<template>
  <el-dialog
    :visible.sync="dialogFormVisible"
    :before-close="handleClose"
    :class="{'mobile-el-dialog': showMobilePage}"
    class="large-common-dialog-size batch-dynamic">
    <div id="fullarea" :style="isFullscreen?{padding: '30px'}:''" class="fullarea">
      <div style="display:flex;align-items:center;">
        <Title :title="`${isEdit?'编辑':'添加'}${requestType ==='income'?'收入':'成本'}项`" font-size="16px">
          <tipIcon content="点击对应区域即可编辑" class="ml5"></tipIcon>
        </Title>
        <i title="全屏" class="el-icon-full-screen" style="font-size:16px;color:#406EFF;cursor:pointer;margin-right:30px;" @click="switchFullscreen"/>
      </div>
      <div :style="{maxHeight: tableHeight + 'px'}" class="dialog-scroll">
        <rowEditTable
          v-if="resetTable"
          ref="dynamicEditTableRef"
          v-model="tableList"
          :order-private-id="orderPrivateId"
          :list-setting="requestType ==='income'?listSetting:costSetting"
          :is-edit="true"
          :show-delete-btn="!isEdit"
          :show-add-btn="!isEdit"
          :custom-valid-key="[{validKey:'supplierId',associatedKey:'costItemId'}]"
          :default-params="defaultParams"
          :show-copy-btn="!isEdit"
          :append-to-body="!isFullscreen"
          :is-fill="isFill"
          :add-btn-style="{height:'30px',fontSize: '14px'}"
          :btn-text="requestType ==='income'?'添加收入项':'添加成本项'"
          @scrollSelectChange="scrollSelectChange"
          @orderPrivateIdChange="orderPrivateIdChange"
          @selectChange="dropdownBoxChange"/>
      </div>
      <div class="btn-container">
        <el-button type="primary" class="ok-btn" size="small" @click="handelOk">确定</el-button>
        <el-button type="info" class="cancel-btn" size="small" @click="handleClose">取消</el-button>
      </div>
    </div>

  </el-dialog>
</template>

<script>
import Title from '@/components/Title';
import rowEditTable from '@/components/Common/rowEditTable';
// api
import { getProjectTypes } from '@/api/project';
import { channelList } from '@/api/select';
import { costList } from '@/api/config';
import { batchAddIncome, batchEditIncome, batchAddCost, batchEditCost } from '@/api/project';
import { getUserList } from '@/api/user';
// tool
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';
import { Message } from 'element-ui';

export default {
  components: { Title, rowEditTable },
  props: {
    requestType: {
      type: String,
      default: 'income' // income / cost
    },
    projectId: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      projectTypesOptions: [],
      costItemOptions: [],
      channelList: [],
      tableList: [],
      isEdit: false,
      dialogFormVisible: false,
      tableHeight: '',
      isFill: true,
      isFullscreen: false,
      resetTable: true,
      orderPrivateId: 1

    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    defaultParams() {
      const params = { isAuto: 1, proposerId_hideList: [{ id: this.userInfo.id, userName: this.userInfo.userName }] };
      if (this.requestType !== 'income') {
        params.proposerId = this.userInfo.id;
        params.proposer = this.userInfo.userName;
      }
      return params;
    },
    listSetting() {
      const projectTypesOptions = this.projectTypesOptions;
      const costItemOptions = this.costItemOptions;
      const channelListData = this.channelList;
      return [
        { label: '下单日期', keyword: 'orderDate', width: '150px', type: 'datepicker', isRequired: true },
        { label: '项目类型', keyword: 'projectType', options: projectTypesOptions, type: 'select', renderType: 'filter', isRequired: true, width: '120px' },
        { label: '含税金额(元)', keyword: 'taxAmount', width: '130px', type: 'inputNumber', isRequired: true },
        { label: '收入说明', keyword: 'incomeRemark', width: '120px', maxlength: 200, type: 'inputText', isRequired: false },
        { label: '含税成本(元)', keyword: 'costAmount', width: '120px', type: 'inputNumber', isRequired: false },
        { label: '成本项', keyword: 'costItemId', options: costItemOptions, linkDisabled: '_costDisabled', type: 'select', renderType: 'filter', isRequired: false, width: '120px' },
        {
          label: '申请人',
          type: 'scrollSelect',
          width: '120px',
          keyword: 'proposerId',
          isRequired: false,
          keyName: 'id',
          labelName: 'userName',
          renderKeyword: 'proposer',
          notShowClear: true,
          loadmoreMethod: getUserList,
          associatedKey: 'costItemId',
          renderType: 'user',
          extendParams: {
            type: 1
          }
        },
        { label: '成本说明', keyword: 'costExplain', width: '120px', linkDisabled: '_costDisabled', maxlength: 200, type: 'inputText', isRequired: false, associatedKey: 'costItemId' },
        { label: '供应商', keyword: 'supplierId', linkField: 'discount', linkDisabled: '_costDisabled', options: channelListData, labelName: 'value', type: 'select', renderType: 'filter', isRequired: false, width: '120px', associatedKey: 'costItemId', renderKeyword: 'value' },
        { label: '可抵扣税率', keyword: 'discount', width: '125px', type: 'inputText', linkDisabled: ['isAuto', '_costDisabled'], placeholder: '由供应商获取', associatedKey: 'costItemId' },
        { label: '自动', keyword: 'isAuto', type: 'switch', linkDisabled: '_costDisabled', renderType: 'switch' }
      ];
    },
    costSetting() {
      const costItemOptions = this.costItemOptions;
      const channelListData = this.channelList;
      return [
        { label: '成本项', keyword: 'costItemId', options: costItemOptions, type: 'select', renderType: 'filter', isRequired: true, width: '120px' },
        {
          label: '申请人',
          type: 'scrollSelect',
          width: '120px',
          keyword: 'proposerId',
          isRequired: false,
          keyName: 'id',
          notShowClear: true,
          labelName: 'userName',
          renderKeyword: 'proposer',
          renderType: 'user',
          loadmoreMethod: getUserList,
          extendParams: {
            type: 1
          }
        },
        { label: '说明', keyword: 'costExplain', width: '150px', maxlength: 200, type: 'inputText', isRequired: true },
        { label: '含税成本(元)', keyword: 'costAmount', type: 'inputNumber', isRequired: false },
        { label: '供应商', keyword: 'supplierId', linkField: 'discount', options: channelListData, labelName: 'value', type: 'select', renderType: 'filter', isRequired: true, width: '120px', renderKeyword: 'value' },
        { label: '可抵扣税率', keyword: 'discount', width: '125px', type: 'inputText', linkDisabled: 'isAuto', placeholder: '由供应商获取' },
        { label: '自动', keyword: 'isAuto', type: 'switch', renderType: 'switch' }
      ];
    }
  },
  watch: {
    // 全屏改变时，重启表格
    isFullscreen: function() {
      this.resetTable = false;
      this.$nextTick(() => {
        this.resetTable = true;
      });
    }
  },
  created() {
    this.getProjectTypeOtions();
    this.getCostList();
    this.getChannel();
  },
  destroyed() {
    window.onresize = null;
  },
  mounted() {
    this.$nextTick(() => {
      window.onresize = this.setFullScreen;
    });
  },
  methods: {
    // <!-- 收入项的成本结算状态为待结算(0)或已忽略(5)时才能编辑 -->
    isCanEdit(item) {
      if (this.requestType === 'income') {
        return item.settlementStatus === 0 || item.settlementStatus === 5;
      }
      return true;
    },
    openDialog(list = [{ isAuto: 1, orderPrivateId: 1 }], isEdit = false) {
      const tableList = _.cloneDeep(list);
      // 项目收入项里面的成本相关字段
      tableList.forEach(i => {
        i.orderPrivateId = this.orderPrivateId++;
        if (i.orderDate) {
          i.orderDate = i.orderDate.toString().length === 10 ? i.orderDate * 1000 : i.orderDate;
        }
        if (i.costAmount) i.costAmount = this.switchMoney(1, i.costAmount);
        if (i.taxAmount) i.taxAmount = this.switchMoney(1, i.taxAmount);
        if (i.supplier && i.supplier.id) {
          i.supplierId = i.supplier.id;
        }
        if (this.requestType === 'income') {
          i.settlementStatus = i.settlementStatus || 0;
          i._costDisabled = !this.isCanEdit(i);
        }
        if (!isEdit) { // 3.0.2申请人,默认当前用户
          i.proposerId_hideList = [{
            id: this.userInfo.id,
            userName: this.userInfo.userName
          }];
          if (this.requestType !== 'income') {
            i.proposerId = Number(this.userInfo.id);
            i.proposer = this.userInfo.userName;
          }
        } else {
          if (i.costItemId) {
            i.proposerId_hideList = [{
              id: i.proposerId,
              userName: i.proposer
            }];
          }
        }
      });
      if (isEdit) {
        this.isFill = tableList.length > 1;
      } else {
        this.isFill = true;
      }
      const clientHeight = window.innerHeight;
      this.tableHeight = (clientHeight * 3) / 5;
      this.tableList = tableList;
      this.isEdit = isEdit;
      this.dialogFormVisible = true;
    },
    orderPrivateIdChange(num) {
      if (!num) return;
      this.orderPrivateId = num;
    },
    scrollSelectChange(keyword, data) { // 人员赋值
      if (keyword === 'proposerId') {
        const rowIndex = this.getCurRowIndex(data, 'orderPrivateId');
        this.tableList[rowIndex].proposerId_hideList = [{
          id: data.id,
          userName: data.userName
        }];
      }
    },
    // 选择成本回填申请人
    dropdownBoxChange(data) {
      const rowIndex = this.getCurRowIndex(data.item);
      switch (data.key) {
        case 'costItemId': // 下单平台
          if (data.item && !data.item.proposerId && data.item.costItemId) {
            this.tableList[rowIndex].proposerId_hideList = [{
              id: this.userInfo.id,
              userName: this.userInfo.userName
            }];
            this.$set(this.tableList[rowIndex], 'proposerId', this.userInfo.id);
          }
          break;
      }
    },
    // 获取当前行数据下标
    getCurRowIndex(rowData, specifyID = '') {
      if (specifyID) { // 指定id
        return this.tableList.findIndex(item => item[specifyID] === rowData[specifyID]);
      }
      if (rowData.id) {
        return this.tableList.findIndex(item => item.id === rowData.id);
      }
      return this.tableList.findIndex(item => item.orderPrivateId === rowData.orderPrivateId);
    },
    handleClose() {
      this.dialogFormVisible = false;
      this.exitFull();
      this.isFullscreen = false;
      this.tableList = [];
      this.$refs.dynamicEditTableRef.clearError();
      this.orderPrivateId = 1;
    },
    handelOk() {
      const tableList = JSON.parse(JSON.stringify(this.tableList));
      const params = {
        projectId: this.projectId,
        incomeList: tableList
      };
      const temp = [];
      for (let i = 0; i < tableList.length; i++) {
        const costItem = this.costItemOptions.find(item => item.costId === tableList[i].costItemId);
        if (costItem) {
          tableList[i].canBeZero = costItem.canBeZero;
          if (Number(tableList[i].costAmount) === 0 && !tableList[i].canBeZero) {
            temp.push(`第${i + 1}行的含税成本不能为0`);
          }
          if (tableList[i].canBeZero && tableList[i].costAmount !== 0 && !tableList[i].costAmount) {
            temp.push(`第${i + 1}行的含税成本不能为空`);
          }
        }
      }
      if (temp.length) {
        const message = temp.map(item => {
          return '<span style="display:inline-block;ling-height: 20px;margin-bottom:6px">' + item + '</span>';
        }).join('<br/>');
        Message({
          type: 'warning',
          dangerouslyUseHTMLString: true,
          message: message
        });
        return true;
      }
      this.$refs.dynamicEditTableRef.validate().then(res => {
        if (this.requestType === 'income') {
          params.incomeList.forEach(i => {
            i.costAmount = this.switchMoney(2, i.costAmount);
            i.taxAmount = this.switchMoney(2, i.taxAmount);
            i.orderDate = i.orderDate.toString().length === 13 ? Math.round(i.orderDate / 1000) : i.orderDate;
          });
          if (!this.isEdit) {
            this.batchCreateIncome(params);
          } else {
            this.batchEditIncome(params);
          }
        } else {
          params.incomeList.forEach(i => {
            i.costAmount = this.switchMoney(2, i.costAmount);
          });
          params.costList = params.incomeList;
          delete params.incomeList;
          if (!this.isEdit) {
            this.batchCreateCost(params);
          } else {
            this.batchEditCost(params);
          }
        }
      }).catch(e => {
        ElMessage.error('请检查信息是否填写完整');
      });
    },
    batchCreateIncome(params) {
      batchAddIncome(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('创建成功');
          this.$emit('freshData');
          this.handleClose();
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    batchEditIncome(params) {
      batchEditIncome(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('编辑成功');
          this.$emit('freshData');
          this.handleClose();
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    batchCreateCost(params) {
      batchAddCost(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('创建成功');
          this.$emit('freshData');
          this.handleClose();
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    batchEditCost(params) {
      batchEditCost(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('编辑成功');
          this.$emit('freshData');
          this.handleClose();
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    // 获取select 列表
    getProjectTypeOtions() {
      const params = {
        type: this.requestType === 'income' ? 0 : 1
      };
      getProjectTypes(params).then(res => {
        this.projectTypesOptions = res.data;
      });
    },
    getCostList() {
      const params = {
        page: 1,
        perPage: 100,
        costBelong: 1
      };
      costList(params).then(res => {
        if (res.data && res.data.items) {
          res.data.items.forEach(i => {
            i.id = i.costId;
            i.name = i.costName;
          });
          this.costItemOptions = res.data.items;
        }
      }).catch(() => {
      });
    },
    // 获取供应商的列表
    getChannel() {
      channelList().then(res => {
        this.channelList = res.data;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    // 分转元， 元转分
    switchMoney(type, amount) {
      if (type === 1) { // 转换成元
        if (amount) {
          return amount / 100;
        } else {
          return amount;
        }
      }
      if (type === 2) { // 转换成分
        if (amount) {
          return Math.round(amount * 100);
        } else {
          return amount;
        }
      }
    },
    /** 全屏功能 */
    exitFull() {
      const isFull = window.fullScreen || document.webkitIsFullScreen;
      if (isFull) {
        if (document && document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
    },
    setFullScreen() {
      const isFull = window.fullScreen || document.webkitIsFullScreen;
      this.isFullscreen = isFull;
    },
    switchFullscreen() {
      const fullarea = document.getElementById('fullarea');
      // 利用屏幕分辨率和window对象的内高度来判断兼容IE
      // const winFlag = window.innerHeight === window.screen.height;
      // 利用window全屏标识来判断 -- IE无效
      const isFull = window.fullScreen || document.webkitIsFullScreen;
      this.isFullscreen = !isFull;
      if (isFull) { // 退出全
        this.exitFull();
      } else { // 进入全屏
        if (fullarea.requestFullscreen) {
          fullarea.requestFullscreen();
        } else if (fullarea.webkitRequestFullScreen) {
          fullarea.webkitRequestFullScreen();
        } else if (fullarea.mozRequestFullScreen) {
          fullarea.mozRequestFullScreen();
        } else if (fullarea.msRequestFullscreen) {
          // IE11
          fullarea.msRequestFullscreen();
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.btn-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  .ok-btn {
    width: 120px;
    height: 32px;
    border-radius: 4px;
  }
  .cancel-btn {
    width: 80px;
    height: 32px;
    background: #EFF3FB;
    border-radius: 4px;
    border: none;
    color: #406EFF;
  }
}
.dialog-scroll {
  position: relative;
  @include scrollBar($x: hidden, $y: auto);
}
.fullarea {
  background-color: #fff;
  padding: 24px 24px 32px 24px !important;
  border-radius: 12px;
}
.batch-dynamic {
  &::v-deep {
    .el-dialog__body {
      padding: 0 !important;
    }
  }
}
</style>
